//
//  MainViewController.m
//  CloudWeibo
//
//  Created by CLOUD on 11/14/14.
//  Copyright (c) 2014 Cloud. All rights reserved.
//

#import "MainViewController.h"
#import "HomeViewController.h"
#import "MessageViewController.h"
#import "DiscoverViewController.h"
#import "ProfileViewController.h"
#import "MoreViewController.h"
#import "BaseNavigationController.h"
#import "ThemeButton.h"
#import "UIFactory.h"
#import "CLOUDAppDelegate.h"
#import "SinaWeibo.h"


@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.tabBar setHidden:YES];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self _initViewController];
    [self _initTabBarView];
    
    [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(showUnreadWeiBo:) userInfo:nil repeats:YES];
    
    
}

-(void) showBadge:(Boolean) show
{
    _badgeView.hidden = !show;
}


-(void) showTabbar:(Boolean) show
{
    for (UIView *subView in self.view.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITransitionView")]) {
            if (show) {
                subView.height = ScreenHeight-49-20;
            }else{
                subView.height = ScreenHeight-20;
            }
        }
    }
    [UIView animateWithDuration:0.35 animations:^{
        if (show) {
            _tabBarView.left = 0;
        } else {
            _tabBarView.left = -ScreenWidth;
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_initViewController
{
    _home = [[HomeViewController alloc] init];
    MessageViewController *message = [[[MessageViewController alloc] init] autorelease];
    ProfileViewController *profile = [[[ProfileViewController alloc] init] autorelease];
    DiscoverViewController *discover = [[[DiscoverViewController alloc] init] autorelease];
    MoreViewController *more = [[[MoreViewController alloc] init] autorelease];
    
    NSArray *views = @[_home, message, profile, discover, more];
    
   
    
    NSMutableArray *viewControllers = [NSMutableArray arrayWithCapacity:5];
    
    for (UIViewController *viewController in views) {
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:viewController];
        [viewControllers addObject:nav];
        [nav release];
        nav.delegate = self;
    }
    
    self.viewControllers =viewControllers;
}

- (void)_initTabBarView
{
    _tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-49-20, ScreenWidth, 49)];
    //_tabBarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background"]];
    UIImageView *tabbarImageView = [UIFactory createImageView:@"tabbar_background.png"];
    tabbarImageView.frame = _tabBarView.bounds;
    [_tabBarView addSubview:tabbarImageView];
    [self.view addSubview:_tabBarView];
    NSArray *background = @[@"tabbar_home.png",@"tabbar_message_center.png",@"tabbar_profile.png",@"tabbar_discover.png",@"tabbar_more.png"];
    NSArray *heightBackground = @[@"tabbar_home_highlighted.png",@"tabbar_message_center_highlighted.png",@"tabbar_profile_highlighted.png",@"tabbar_discover_highlighted.png",@"tabbar_more_highlighted.png"];
    
    for (int i=0; i<background.count; i++) {
        NSString *image = background[i];
        NSString *highImage = heightBackground[i];
        
        //UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //ThemeButton *button = [[ThemeButton alloc] initWithImage:image highlightedImage:highImage];
        UIButton *button = [UIFactory createButton:image highlited:highImage];
        button.showsTouchWhenHighlighted = YES;
        button.frame = CGRectMake((ScreenWidth/5-30)/2+(ScreenWidth/5*i), (49-30)/2, 30, 30);
        //[button setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
        //[button setImage:[UIImage imageNamed:heightImage] forState:UIControlStateHighlighted];
        button.tag = i;
        [button addTarget:self action:@selector(selectedTab:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:button];
    }
    
    _sliderView = [[UIFactory createImageView:@"tabbar_slider.png"] retain];
    _sliderView.frame = CGRectMake((ScreenWidth/5-15)/2, 5, 15, 44);
    _sliderView.backgroundColor = [UIColor clearColor];
    [_tabBarView addSubview:_sliderView];
    
    
    
}

- (void) refreshUnReadView:(NSDictionary *) result
{
    NSNumber *status = [result objectForKey:@"status"];
    if (_badgeView == nil) {
        _badgeView = [UIFactory createImageView:@"main_badge.png"];
        _badgeView.frame = CGRectMake(64-25, 5, 20, 20);
        [_tabBarView addSubview:_badgeView];
        
        UILabel *badgeLabel = [[UILabel alloc] initWithFrame:_badgeView.bounds];
        badgeLabel.textAlignment = NSTextAlignmentCenter;
        badgeLabel.backgroundColor = [UIColor clearColor];
        badgeLabel.font = [UIFont boldSystemFontOfSize:13.0f];
        badgeLabel.textColor = [UIColor purpleColor];
        badgeLabel.tag = 2018;
        [_badgeView addSubview:badgeLabel];
        [badgeLabel release];
    }
    
    int n = [status intValue];
    
    if (n > 0) {
        UILabel *bagdeLabel = (UILabel *)[_badgeView viewWithTag:2018];
        if (n > 99) {
            n = 99;
        }
        bagdeLabel.text = [NSString stringWithFormat:@"%d", n];
        _badgeView.hidden = NO;
    } else {
        _badgeView.hidden = YES;
    }
}


- (void)loadUnreadData
{
    CLOUDAppDelegate *cloudAppDelegate = (CLOUDAppDelegate *)[UIApplication sharedApplication].delegate;
    SinaWeibo *sinaWeiBo = cloudAppDelegate.sinaWeibo;
    [sinaWeiBo requestWithURL:@"remind/unread_count.json" params:nil httpMethod:@"GET" block:^(NSDictionary *result){
        [self refreshUnReadView:result];
    }];
}

- (void)selectedTab:(UIButton *) button
{
    if (self.selectedIndex == button.tag && button.tag == 0) {
        UINavigationController *homeNavigation = [self.viewControllers objectAtIndex:0];
        HomeViewController *home = [homeNavigation.viewControllers objectAtIndex:0];
        [home refreshWeiBo];
    }
    
    self.selectedIndex = button.tag;
    
    float selectedTabBarX = (button.left +(button.width - _sliderView.width)/2);
    [UIView animateWithDuration:0.2 animations:^{
        _sliderView.left = selectedTabBarX;
    }];
    
}

- (void)showUnreadWeiBo:(NSTimer *) timer
{
    [self loadUnreadData];
}

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn##################");
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [_home loadWeiboData];
    
    
}
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut##################");
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    _home.tableView.hidden = YES;
    [_home.sinaweibo logIn];
}
- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel##################");

}


- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
    int count = navigationController.viewControllers.count;
    if (count == 2) {
        [self showTabbar:NO];
    }else if (count == 1) {
        [self showTabbar:YES];
    }
    
}
@end
